<?php
/**
 * Created by PhpStorm.
 * User: Yui
 * Date: 2017/5/16 0016
 * Time: 16:22
 */

namespace common\models;


use common\services\AliSmsSve;
use yii\base\Model;
use Yii;

class MemberResetPwd extends Model
{
    public $mobile;
    //public $verify_code;
    public $password;
    public $password_repeat;
    public $old_password;
    public $_old_password;

    private $_Member;

    public function rules()
    {
        return [
            [['old_password', 'password', 'password_repeat'], 'required'],

           // ['mobile', 'match', 'pattern' => '/^1[34578]\d{9}$/', 'message' => '手机号码格式错误'],

            //['verify_code', 'string', 'min' => OC['sms_code_len'], 'message' => '验证码至少' . OC['sms_code_len'] . '个字符'],

            [['password', 'password_repeat'], 'string', 'min' => 6],
            ['password', 'compare'],
            ['old_password', 'validateOldPassword', 'message' => '旧密码不正确'],
        ];
    }


    public function validateOldPassword($attribute, $params)
    {

        if (!$this->hasErrors()) {
            if(!Yii::$app->security->validatePassword($this->old_password, $this->_old_password)){
                $this->addError($attribute, '旧密码不正确');
            }
        }
    }

    public function validateCode($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $Member = $this->getMember();
            if (empty($Member)) {
                $this->addError($attribute, '手机号码或验证码错误');
            }
            //检查验证码
            $AliSmsSve = new AliSmsSve();
            $rs = $AliSmsSve->checkVerifyCode($this->mobile, 'reset_password', $this->verify_code);
            if ($rs['code'] !== 0) {
                $this->addError($attribute, $rs['msg']);
                return;
            }
        }
    }

    public function getMember()
    {
        if ($this->_Member === null) {
            $this->_Member = Member::findByMobile($this->mobile);
        }
        return $this->_Member;
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return (new Member())->attributeLabels();
    }
}